/*
 * main.js
 */

//主流浏览器 firefox ， chrome 等等  比较简单
function getCurPos(_textarea){

var pos = {};

    if('number' === typeof _textarea.selectionStart){

        pos.start = _textarea.selectStart; //如果用户没有建立一个文本选区， selectStart为光标当前所在的位置。 pos.start == pos.end

        pos.end = _textarea.selectEnd;

    }

    else if(document.selection){

        //IE 6,7,8

    }

}
function setCurPos(_textarea , pos ){

    if(_textarea.setSelectionRange){

        _textarea.focus();//先聚焦到该输入框

        _textarea.setSelectionRange(pos.start,pos.start);

    }

    else if(_textarea.createTextRange){

        //IE 6,7,8

    }

}

//兼容IE6,7,8的处理

function getCurPos(_textarea){

var pos = {};

    if('number' === typeof _textarea.selectionStart){//chrome 、firefox ……

        pos.start = _textarea.selectionStart;//如果用户没有建立一个文本选区， selectStart为光标当前所在的位置。 pos.start == pos.end

        pos.end = _textarea.selectionEnd;

 

    }

    else if(document.selection){//IE 6,7,8

        //获取用户的选区

        var userRange = document.selection.createRange();

        //判断选区是否为改 textarea 

        if(userRange.parentElement() == _textarea){

            //创建一个文本区 createTextRange只在IE中有效

            var textRange = document.body.createTextRange();

            //移动文本区到 _textarea

            textRange.moveToElementText(_textarea);//此时 textRange.text = _textarea.value ,及textRange选区涵盖了 整个_textarea

            

            //接下来，调整文本选区textRange的区域，与userRange的区域重合 

            var start = 0;

            for(start = 0 ; textRange.compareEndPoints('StartToStart',userRange) < 0 && textRange.moveStart('character',1) !== 0 ; ++start ){

                //计算 \n

                if(_textarea.value.charAt(start) == '\n'){

                    ++start;

                }

            }

            pos.start = start ;//如果用户没有建立一个文本选区， selectStart为光标当前所在的位置。 pos.start == pos.end

            if(userRange.length != undefined){

                pos.end = start + userRange.length;

            }

            else{

                pos.end = start;

            }

        }

        

    }

    return pos;

}

// set cursor position  type = point(只移动光标到某点) | range(选中文本) 

function setCurPos(_textarea , pos , type){

    if(_textarea.setSelectionRange){//chrome 、 firefox ……

        _textarea.focus();//先聚焦到该输入框

        

        if(type != undefined && type == 'range' ){

        

            //1、方法一

            //_textarea.setSelectionRange(pos.start,pos.end);//载入选区

            

            //2、方法二

            _textarea.selectionStart = pos.start;

            _textarea.selectionEnd = pos.end;

        }

        else{

            _textarea.setSelectionRange(pos.end,pos.end);

        }

        

    }

    else if(_textarea.createTextRange){//IE 6,7,8

        //在_textarea 中直接创建 文本选区

        var textRange = _textarea.createTextRange();

        

        if(type != undefined && type == 'range'){

        

            //1、定位光标位置

            //textRange.move('character',pos.start);//

            //textRange.select();//设为被选中状态

            

            //2、载入选区

            textRange.collapse(true);

            textRange.moveStart('character',pos.start);

            textRange.moveEnd('character',pos.end-pos.start);

            textRange.select();

        }

        else{

            textRange.move('character',pos.end);

            textRange.select();

        }

    }

}

//具体使用环境： 需要在某个<textarea></textarea>中光标出插入一个字符串

function insertStrToTextarea(_textarea,str){

    if(str == undefined || str == ''){

        return false;

    }

    if(document.selection){//IE6,7,8下光标处插入文本的简易方法

        //document.selection.createTextRange()为页面中当前被选中的地方

        document.selection.createTextRange().text = str;

        return true;

    }

    

    var pos = getCurPos(_textarea);

    var str0 = _textarea.value.substring(0,pos.start) , str1 = _textarea.value.substring(pos.end);

    _textarea.value = str0 + str + str1;

    

    pos.end += str.length;

    setCurPos(_textarea,pos,'point');

    return true;

}
	
function show_tags(obj, availableTags, callback){
	if (obj.length)
	{
		obj.autocomplete({
			source: availableTags,
			

			close: function( event, ui ) {
				
			},
			select: function( event, ui ) {
				obj.unbind('blur');
				if (obj.hasClass('multiple_tag'))
				{
					//console.log(ui.item.true_value);
					obj.parent().find('input[type="hidden"]').val(ui.item.true_value);
				}
				obj.attr('readonly', true);
				
				if (callback) callback(event, ui);
				
			},
			

		});
		
		obj.on('click', function(){
			obj.attr('readonly', false);
			obj.val('');
		});
		
		obj.keypress(function(){
			$(this).unbind('blur');
			obj.blur(function(){
				$(this).val('');
			});
		});
		

		
	}
}

function common_show_success(str, duration)
{
	var tpl = $('<div class="alert alert-success" style="position:fixed; top: 0; left: 50%; margin-left: -280px;  width: 560px; z-index: 9999;"><i class="ace-icon fa fa-check"></i> '+ str +'</div>');
	$('body').append(tpl);
	setTimeout(function(){
		tpl.animate({opacity: 0, top: '-35px'}, 1000, function(){
			$(this).remove();
		})
	}, (duration || 1200));
}

function common_show_error(str, duration)
{
	var tpl = $('<div class="alert alert-danger" style="position:fixed; top: 0; left: 50%; margin-left: -280px;  width: 560px; z-index: 9999;"><i class="ace-icon fa fa-times"></i> '+ str +'</div>');
	$('body').append(tpl);
	setTimeout(function(){
		tpl.animate({opacity: 0, top: '-35px'}, 1000, function(){
			$(this).remove();
		})
	}, (duration || 1200));
}

function common_ajax_submit_form(form_obj, options, callback)
{
	var options = $.extend({
		validate_rules_options:{
		
		},
		validate_messages_options:{
		
		},
		ajax_url: ''
	}, options);
	if (form_obj.length)
	{
		form_obj.validate({
			errorElement: 'div',
			errorClass: 'help-block',
			focusInvalid: true,
			rules: options.validate_rules_options,

			messages: options.validate_messages_options,

			highlight: function (e) {
				$(e).closest('.form-group').removeClass('has-info').addClass('has-error');
			},
	
			success: function (e) {
				$(e).closest('.form-group').removeClass('has-error');
				$(e).remove();
			},


			submitHandler: function (form) {
				
				$('[type="submit"]', form).prop('disabled', true);
					
				var form_options = {
					dataType: 'json',
					url: (options.ajax_url || $(form).attr('data-url')),
					success: function(res){
						callback(res, form);
						$('button[type="submit"]', form).prop('disabled', false);
					},
					error: function(){
						
						$('button[type="submit"]', form).prop('disabled', false);
					}
				}
				
				$(form).ajaxSubmit(form_options);
				return false;
			},
			invalidHandler: function (form) {
			}
		});
	}
	
	
	
}

$(document).ready(function() {
	
	//------------------------------ common --------------------------------
	
	if ($('.mask_price').length)
	{
		$('.mask_price')[0].style.imeMode = 'disabled';
		$('.mask_price').inputmask('decimal', { digits: 2, allowMinus: false });
	}
	
	$(document).on('click', 'th input:checkbox' , function(){
		var that = this;
		$(this).closest('table').find('tr > td:first-child input:checkbox')
		.each(function(){
			this.checked = that.checked;
			$(this).closest('tr').toggleClass('selected');
		});
	});
	
	
	if ($('.ace_editor').length)
	{
		
		$('.ace_editor').ace_wysiwyg({
		toolbar:
		[
			'font',
			null,
			'fontSize',
			null,
			{name:'bold', className:'btn-info'},
			{name:'italic', className:'btn-info'},
			{name:'strikethrough', className:'btn-info'},
			{name:'underline', className:'btn-info'},
			null,
			{name:'insertunorderedlist', className:'btn-success'},
			{name:'insertorderedlist', className:'btn-success'},
			{name:'outdent', className:'btn-purple'},
			{name:'indent', className:'btn-purple'},
			null,
			{name:'justifyleft', className:'btn-primary'},
			{name:'justifycenter', className:'btn-primary'},
			{name:'justifyright', className:'btn-primary'},
			{name:'justifyfull', className:'btn-inverse'},
			null,
			{name:'createLink', className:'btn-pink'},
			{name:'unlink', className:'btn-pink'},
			null,
			{name:'insertImage', className:'btn-success'},
			null,
			'foreColor',
			null,
			{name:'undo', className:'btn-grey'},
			{name:'redo', className:'btn-grey'},
			'viewSource',
			'insertSquare'
		],
		'wysiwyg': {
			keypress: function(){
				var textarea = this.toolbarSelector.parent().find('textarea'),
					data = this.toolbarSelector.parent().find('.ace_editor').html();
					textarea.val(data);
			}
		}
	}).prev().addClass('wysiwyg-style2');
	}
	
	if ($('.ace_tooltip').length)
	{
		$('.ace_tooltip').tooltip({
			show: null,
			position: {
				my: "left top",
				at: "left bottom"
			}


		});
		
	}

	if ($('.input-daterange').length)
	{
		$('.input-daterange').datepicker({
		format: 'yyyy-mm-dd',
		autoclose:true});
	}

	
	if ($('.ace_date_timepicker').length)
	{
		$('.ace_date_timepicker').datetimepicker({
			format: 'YYYY-MM-DD HH:mm'

		});
	}

	if ($('.ace_birthday_picker').length)
	{
		$('.ace_birthday_picker').datepicker({
			format: 'yyyy-mm-dd'
		})
	}
	
	$('table tr').click(function(){
		$(this).parents('table').find('td').css({
			backgroundColor: '',
			color: ''
		});
		$(this).find('td').css({
			backgroundColor: '#E4EFC9',
			color: '#000'
		});
	});
	
	$('.dialog_edit').click(function(){
		var self = $(this),
		url = self.attr('data-url');
		$('#dialog_edit').modal('show');
		$.ajax({
			url: url,
			success: function(res){
				
				$('#dialog_edit .modal-body').html(res);
			}
		})
	});
	
	$('.dialog_full_edit').click(function(){
		var self = $(this),
		url = self.attr('data-url');
		$('#dialog_edit').modal('show');
		$.ajax({
			url: url,
			success: function(res){
				
				$('#dialog_edit .modal-body').html(res);
				
				$('#dialog_edit .modal-dialog').css({
					width: $(window).width() - 100
					
				})
			}
		})
	});
	
	if ($('#submitMessage').length)
	{	
		setTimeout(function(){
			$('#submitMessage').animate({opacity: 0, top: '-35px'}, 1000, function(){
				$(this).remove();
			})
		}, 1200);
	}
	
	//bind delete Button
	$('.btn_single_del').click(function(e){
		e.preventDefault();
		var self = $(this);
		if (window.confirm('确认删除操作？')){
			$.ajax({
				dataType: 'json',
				url: self.attr('data-url'),
				success: function(res){
					if (res.code == '1'){
						common_show_success('删除成功');
						setTimeout(function(){
							location.href = location.href;
						}, 1500);
					}else{
						common_show_error(res.message);
					}
				}
			})
		}
	});
	
	//bind update button
	$('.btn_update').click(function(e){
		e.preventDefault();
		var self = $(this);
		if (window.confirm('确定更新操作？')){
			$.ajax({
				dataType: 'json',
				url: self.attr('data-url'),
				success: function(res){
					if (res.code == '1'){
						common_show_success('更新成功');
						setTimeout(function(){
							location.href = location.href;
						}, 1500);
					}else{
						common_show_error(res.message);
					}
				}
			})
		}
	});

	//驳回审核
	$('.btn_uncheck').click(function(e){
		var self = $(this);
		$('#dialog_uncheck').modal('show');
		$('#dialog_uncheck [name="id"]').val(self.attr('data-id'));

	});

	//批量移动到回收站
	$('.btn_batch_remove').click(function(){

		var self = $(this);
		var checkbox = $(this).parent().parent().parent().find('td').find('input:checkbox:checked');
		if (checkbox.length)
		{
			if (window.confirm('确认批量移动到回收站操作？')){
			
				var ids = [];
				checkbox.each(function(){
					ids.push($(this).attr('data-id'));
				});

				$.ajax({
					dataType: 'json',
					url: self.attr('data-url'),
					data: {
						id: ids.join(',')
					},
					success: function(res){
						if (res.code == '1')
						{
							common_show_success('批量移动到回收站成功');
							setTimeout(function(){
								location.href = location.href;
							}, 1000);
						}
						else
						{
							common_show_error(res.message);
						}
						
					}
				});
			}
			
		}
		else
		{
			common_show_error('请勾选至少一项');
		}



	});

	//批量审核
	$('.btn_batch_check').click(function(){

		var self = $(this);
		var checkbox = $(this).parent().parent().parent().find('td').find('input:checkbox:checked');
		if (checkbox.length)
		{
			if (window.confirm('确认批量审核操作？')){
			
				var ids = [];
				checkbox.each(function(){
					ids.push($(this).attr('data-id'));
				});

				$.ajax({
					dataType: 'json',
					url: self.attr('data-url'),
					data: {
						id: ids.join(','),
						check_status: '1'
					},
					success: function(res){
						if (res.code == '1')
						{
							common_show_success('批量审核成功');
							setTimeout(function(){
								location.href = location.href;
							}, 1000);
						}
						else
						{
							common_show_error(res.message);
						}
						
					}
				});
			}
			
		}
		else
		{
			common_show_error('请勾选至少一项');
		}



	});

	//批量驳回审核
	$('.btn_batch_uncheck').click(function(){

		var self = $(this);
		var checkbox = $(this).parent().parent().parent().find('td').find('input:checkbox:checked');
		if (checkbox.length)
		{
			if (window.confirm('确认批量驳回审核操作？')){
			
				var ids = [];
				checkbox.each(function(){
					ids.push($(this).attr('data-id'));
				});

				$.ajax({
					dataType: 'json',
					url: self.attr('data-url'),
					data: {
						id: ids.join(','),
						check_status: '2'
					},
					success: function(res){
						if (res.code == '1')
						{
							common_show_success('批量驳回审核成功');
							setTimeout(function(){
								location.href = location.href;
							}, 1000);
						}
						else
						{
							common_show_error(res.message);
						}
						
					}
				});
			}
			
		}
		else
		{
			common_show_error('请勾选至少一项');
		}



	});
	

	
});